package com.action.wx.wechat;

import com.action.wx.common.CommonAction;
import com.common.BaseAction;
import com.service.member.MemberService;
import com.service.wxconfig.WxConfigService;
import com.util.SHA1;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 微信相关
 */
@Controller
@RequestMapping("wx/wechat")
public class WechatAction extends BaseAction{
    Logger logger = Logger.getLogger(CommonAction.class);
    private String Token = "123456789abcdef";
    @Autowired
    private WxConfigService wxConfigService;


    @ResponseBody
    @RequestMapping(value="/chat")
    public void mainService(HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean isGet = "get".equals(request.getMethod().toLowerCase());
        if (isGet) {
            access(request, response);
        } else {
            // 接收消息并返回消息
            String respMessage = wxConfigService.processRequest(request);
            // 响应消息
            PrintWriter out = response.getWriter();
            out.print(respMessage);
            out.close();
        }
    }


    private String access(HttpServletRequest request, HttpServletResponse response) {
        // 验证URL真实性
        logger.info("进入验证access");
        String signature = request.getParameter("signature");// 微信加密签名
        String timestamp = request.getParameter("timestamp");// 时间戳
        String nonce = request.getParameter("nonce");// 随机数
        String echostr = request.getParameter("echostr");// 随机字符串
        /*// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
     		if (SignUtil.checkSignature(signature, timestamp, nonce)) {
     			System.out.println("微信服务验证成功！"+echostr);
     			return echostr;
     		}
     		System.out.println("微信服务验证失败！");
     		return null;*/

        List<String> params = new ArrayList<String>();
        params.add(Token);
        params.add(timestamp);
        params.add(nonce);
        // 1. 将token、timestamp、nonce三个参数进行字典序排序
        Collections.sort(params, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        // 2. 将三个参数字符串拼接成一个字符串进行sha1加密
        String temp = SHA1.encode(params.get(0) + params.get(1) + params.get(2));
        if (temp.equals(signature)) {
            try {
                response.getWriter().write(echostr);
                logger.info("成功返回 echostr：" + echostr);
                System.out.println("成功返回 echostr：" + echostr);
                return echostr;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        logger.info("失败 认证");
        System.out.println("失败 认证");
        return null;
    }
}
